<?php
require_once 'HTTP/Request2.php';

class OaHscHttpRequest
{
    private $_logger;
    private $_httpRequest;
    private $_params = array(
        'SERVICE_NAME' => '',    // 服务名，对Open网站来说为M_APP1
        'ret_type' => 'json',          // 返回数据格式
        'key' => 'abc',                   // 要查询的库表名称，格式为db.table
        'cmd' => ''	                   // 协议号
    );
    
    public function __construct($url, $serviceName, $method = HTTP_Request2::METHOD_GET, 
        $params = array(), $logger = null)
    {
        $params['SERVICE_NAME'] = $serviceName;
        $this->_params = array_merge($this->_params, $params);
        $this->_httpRequest = new HTTP_Request2($url, $method, array(
            'connect_timeout' => 2,
            'timeout' => 5,
        ));
        if (is_null($logger)) {
            $this->_logger = Log::factory('null');
        } else {
            $this->_logger = $logger;
        }
    }
    
    public function setServiceName($serviceName)
    {
        $this->_params['SERVICE_NAME'] = $serviceName;
        return true;
    }
    
    public function setRetType($retType)
    {
        $this->_params['ret_type'] = $retType;
        return true;
    }
    
    public function setKey($key)
    {
        $this->_params['key'] = $key;
        return true;
    }
    
    public function setCmd($cmd)
    {
        $this->_params['cmd'] = $cmd;
        return true;
    }
    
    public function setMethod($method)
    {
        return $this->_httpRequest->setMethod($method);
    }
    
    public function setConnectTimeout($timeout)
    {
        return $this->_httpRequest->setConfig('connect_timeout', $timeout);
    }
    
    public function setTimeout($timeout)
    {
        return $this->_httpRequest->setConfig('timeout', $timeout);
    }
    
    public function send($params = array())
    {
        $params = array_merge($this->_params, $params);
        $this->_logger->debug($params);
        $url = $this->_httpRequest->getUrl();
        $url->setQueryVariables($params);
        try {
            $body = $this->_httpRequest->send()->getBody();
        } catch (HTTP_Request2_Exception $e) {
            $errno = $e->getCode();
            $error = $e->getMessage();
            $this->_logger->err("send request failed: errno-$errno, error-$error");
            return false;
        }
        $this->_logger->debug($body);
        $result = json_decode($body, true);
        if (is_null($result)) {
            $this->_logger->err("json decode body failed: $body");
            return false;
        }
        return $result;
    }
    
    /**
     * 透传SQL协议，中间层直接把SQL递交给数据库
     * @param string $sql
     * @return array|boolean
     */
    public function sendSql($sql, $cmd = 'M1')
    {
        return $this->send(array(
            'cmd' => $cmd,
            'sql' => $sql
        ));
    }
}